package com.kim.chapter10.http.xml.codec;

import com.kim.chapter10.http.xml.XStreamUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.Charset;

public abstract class AbstractHttpXmlDecoder<T> extends
        MessageToMessageDecoder<T> {

    private Class<?> clazz;
    private boolean isPrint;
    private final static String CHARSET_NAME = "UTF-8";
    private final static Charset UTF_8 = Charset.forName(CHARSET_NAME);

    protected AbstractHttpXmlDecoder(Class<?> clazz) {
        this(clazz, false);
    }

    protected AbstractHttpXmlDecoder(Class<?> clazz, boolean isPrint) {
        this.clazz = clazz;
        this.isPrint = isPrint;
    }

    protected Object decode0(ChannelHandlerContext arg0, ByteBuf body)
            throws Exception {
        /**
         * 从HTTP的消息体中获取请求码流
         */
        String content = body.toString(UTF_8);
        //根据码流开关决定是否打印码流内容
        if (isPrint) {
            //增加开关是为了方便定位问题，实际项目中，需要打印到日志中
            System.out.println("The body is : " + content);
        }
        //将XML转换为POJO对象
        Object result = XStreamUtil.xmlToBean(content, clazz);
        return result;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        // 释放资源
        System.out.println(cause.getMessage());
    }
}
